#include "SelectionTool.h"
#include "SelectRegionControl.h"



SelectionTool::SelectionTool (QWidget * parent) : AbstractTool (parent), 
  _mouseDragRegion (4), _isInAction (false)
{
  setText (tr ("Selection"));
}



SelectionTool::~SelectionTool ()
{

}



void SelectionTool::_startSelection (const QPoint & point)
{
  __pWork->setSelectRegion (NULL);
  for (int i = 0; i < 4; ++i)
    _mouseDragRegion.setPoint (i, point);
  _isInAction = true;
  emit repaintViewport ();
}



void SelectionTool::_changeSelection (const QPoint & point)
{
  QPoint startPoint = _mouseDragRegion.point (0);
  _mouseDragRegion.setPoint (1, point.x (), startPoint.y ());
  _mouseDragRegion.setPoint (2, point);
  _mouseDragRegion.setPoint (3, startPoint.x (), point.y ());
  emit repaintViewport ();
}



void SelectionTool::_finishSelection ()
{
  if (_mouseDragRegion.point (0) == _mouseDragRegion.point (2))
    __pWork->setSelectRegion (NULL);
  else
  {
    QRect boundingRect = _mouseDragRegion.boundingRect ();
    boundingRect.setBottom (boundingRect.bottom () - 1);
    boundingRect.setRight (boundingRect.right () - 1);
    Ptr< SelectRegion > pSelectRegion = SelectRegionControl::getSingleton ()
      .createRectRegion (boundingRect);
    __pWork->setSelectRegion (pSelectRegion);
  }
  _isInAction = false;
  emit repaintViewport ();
}



void SelectionTool::_canvasMousePressedEvent (QPoint loc, QMouseEvent * event)
{
  if (event->buttons () == Qt::LeftButton)
    _startSelection (loc);
}



void SelectionTool::_canvasMouseMovedEvent (QPoint loc, QMouseEvent * event)
{
  if (event->buttons () == Qt::LeftButton)
    _changeSelection (loc);
}



void SelectionTool::_canvasMouseReleasedEvent (QPoint loc, QMouseEvent * event)
{
  if (event->buttons () == 0 && event->button () == Qt::LeftButton)
    _finishSelection ();
}



void SelectionTool::_canvasPaintingEvent (QPainter & painter)
{
  if (_isInAction)
  {
    // Draw selection border
//     painter.save ();
//     QPoint imageO = __pViewportCtrl->imageToViewport (QPoint ());
//     painter.translate (imageO);
    QVector<qreal> dashes;
    dashes.push_back (3);
    dashes.push_back (3);
    QPen painterPen;
    painterPen.setDashPattern (dashes);
    painterPen.setColor (QColor (255, 255, 255));
    painter.setPen (painterPen);
    painter.drawPolygon (_mouseDragRegion);
    painterPen.setDashOffset (3);
    painterPen.setColor (QColor (0, 0, 0));
    painter.setPen (painterPen);
    painter.drawPolygon (_mouseDragRegion);
//     painter.restore ();
  }
}



// void SelectionTool::_globalKeyPressedEvent (QKeyEvent * event)
// {
//   if (event->modifiers () & Qt::ControlModifier && event->key () == 'D')
//     cancelSelection ();
// }


